<template>
    <view class="image_list">
        <view class="item" v-for="(item, index) in list" :key="index">
            <up-image :show-loading="true" :src="item" width="144rpx" height="144rpx" radius="16rpx"
                @click="previewImg(index)">
                <template #error>
                    <view style="font-size: 24rpx;">加载失败</view>
                </template>
            </up-image>
            <view class="delicon" @click="delImg(index)">
                <image v-if="!disabled" src="../../static/images/index/icon_delect.png"/>
            </view>
        </view>
        <view class="item upload" v-if="list.length < max && !disabled" @click="chooseImg">
            <up-icon name="plus" color="#9B9B9B" size="18"></up-icon>
            <view class="mt16">选择照片</view>
        </view>
    </view>
</template>

<script setup lang="ts">
import config from '@/utils/config';
import { ref, toRefs, watch } from 'vue';
const { uploadUrl } = config

const emit = defineEmits(['uploadImgSuccess', "deleteImg"])

const props = withDefaults(defineProps<{
    // 回显的图片数组
    imgList?: string[]
    // 是否显示上传按钮
    showUpload?: boolean
    // 最大上传数量
    max?: number
    // 是否显示删除按钮
    showDelete?: boolean
    // 图片不能超过(M)
    maxSize?: number
    // 仅查看
    disabled?: boolean
    // 预览
    preview?: boolean
}>(), {
    imgList: () => [],
    showUpload: true,
    max: 3,
    showDelete: true,
    maxSize: 5,
    disabled: false,
    preview: false
})
const { imgList } = toRefs(props)

const list = ref<string[]>([])

watch(imgList, (newVal, oldval) => {
    list.value = newVal
    // console.log(list.value)
}, { deep: true })

// 删除图片
const delImg = (index: number) => {
    list.value.splice(index, 1)
    emit('deleteImg', index)
}

const chooseImg = () => {
    uni.chooseImage({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: async (chooseImageRes: any) => {
            let tempFiles = chooseImageRes.tempFiles
            // 图片超出最大数量提示
            if (list.value.length + tempFiles.length > props.max) {
                uni.showToast({
                    title: '最多只能上传' + props.max + '张图片',
                    icon: 'none'
                })
                return
            }
            // 图片大小超出
            let flag = tempFiles.every((item: any) => {
                return item.size / 1024 / 1024 <= props.maxSize
            })
            if (!flag) {
                uni.showToast({
                    title: '图片大小不能超过' + props.maxSize + 'M',
                    icon: 'none'
                })
                return
            }
            // 上传图片
            for (let i = 0; i < tempFiles.length; i++) {
                let url: any = await uploadFilePromise(tempFiles[i].path)
                list.value.push(url)
                emit('uploadImgSuccess', url)
            }
        }
    })
}

const uploadFilePromise = (filePath: any) => {
    uni.showLoading({
        title: "正在上传...",
        mask: true
    })
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: uploadUrl,
            filePath: filePath,
            name: 'file',
            header: {
                'Content-Type': 'multipart/form-data',
            },
            formData: {
                'user': '123'
            },
            success: (uploadFileRes) => {
                uni.hideLoading()
                const data = JSON.parse(uploadFileRes.data)
                if (data?.code == 0 && data?.data) {
                    setTimeout(() => {
                        resolve(data.data)
                    }, 500)
                }
            },
            fail: (err) => {
                uni.hideLoading()
                reject(err)
            }
        });
    })
}

// 预览图片
const previewImg = (index: number) => {
    uni.previewImage({
        current: index, // 当前显示图片的http链接
        urls: list.value // 需要预览的图片http链接列表
    });
}

</script>

<style lang="scss" scoped>
.image_list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}

.item {
    width: 144rpx;
    height: 144rpx;
    border-radius: 16rpx;
    margin-left: 24rpx;
    margin-bottom: 16rpx;
    position: relative;

    .delicon {
        width: 48rpx;
        height: 48rpx;
        position: absolute;
        right: -24rpx;
        top: -24rpx;
        image{
            width: 100%;
            height: 100%;
        }
    }
}

.upload {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background: #F2F2F2;
    font-size: 22rpx;
    color: #9B9B9B;
}
</style>